#!/bin/bash

# 后端自动部署脚本 - Systemd 版本

SERVER_HOST="47.104.101.179"
SERVER_USER="root"
SERVER_PATH="/www/智慧物流/backend"
JAR_NAME="logistics-backend-1.0.0.jar"

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}  物流后端 - 自动部署（Systemd）${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""

# 1. Maven 打包
echo -e "${YELLOW}[1/4] Maven 打包中...${NC}"
mvn clean package -DskipTests

if [ $? -ne 0 ]; then
    echo -e "${RED}❌ 打包失败！${NC}"
    exit 1
fi
echo -e "${GREEN}✅ 打包成功${NC}"
echo ""

# 2. 上传 JAR
echo -e "${YELLOW}[2/4] 上传 JAR 到服务器...${NC}"
scp target/${JAR_NAME} ${SERVER_USER}@${SERVER_HOST}:${SERVER_PATH}/

if [ $? -ne 0 ]; then
    echo -e "${RED}❌ 上传失败！${NC}"
    exit 1
fi
echo -e "${GREEN}✅ 上传成功${NC}"
echo ""

# 3. 重启服务
echo -e "${YELLOW}[3/4] 重启服务...${NC}"
ssh ${SERVER_USER}@${SERVER_HOST} "systemctl restart logistics-backend"

if [ $? -ne 0 ]; then
    echo -e "${RED}❌ 重启失败！${NC}"
    exit 1
fi
echo -e "${GREEN}✅ 服务已重启${NC}"
echo ""

# 4. 检查服务状态
echo -e "${YELLOW}[4/4] 检查服务状态...${NC}"
ssh ${SERVER_USER}@${SERVER_HOST} << 'ENDSSH'
    sleep 3
    systemctl status logistics-backend --no-pager -l
    
    echo ""
    echo "最近日志："
    tail -20 /www/智慧物流/backend/logs/app.log
ENDSSH

echo ""
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}✅ 部署完成！${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""
echo -e "API 地址: ${GREEN}http://api.imxyzz2kk.fun${NC}"
echo ""
echo "常用命令："
echo "  查看状态: ssh ${SERVER_USER}@${SERVER_HOST} 'systemctl status logistics-backend'"
echo "  查看日志: ssh ${SERVER_USER}@${SERVER_HOST} 'tail -f ${SERVER_PATH}/logs/app.log'"
echo "  重启服务: ssh ${SERVER_USER}@${SERVER_HOST} 'systemctl restart logistics-backend'"
echo "  停止服务: ssh ${SERVER_USER}@${SERVER_HOST} 'systemctl stop logistics-backend'"
echo ""
